<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\exception\UploadException;
use app\common\library\Upload;
use app\common\model\Acct;
use app\common\model\Address;
use app\common\model\Admin;
use app\common\model\Area;
use app\common\model\Channelapply;
use app\common\model\Custom as ModelCustom;
use app\common\model\shop\Goods;
use app\common\model\shop\Order;
use app\common\model\Systemconfig;
use app\common\model\User;
use app\common\model\user\Channel;
use app\common\model\user\Commission;
use app\common\model\user\Custom;
use app\common\model\user\Withdrawlog;
use app\common\model\Version;
use fast\Random;
use fast\Tree;
use Hyc;
use Jdy;
use think\Cache;
use think\Config;
use think\Hook;
use think\Log;

/**
 * 公共接口
 */
class Common extends Api
{
    protected $noNeedLogin = ['init', 'updateCity', 'updateCustCity', 'updateCustAddressCity', 'yy_notify', 'site_config', 'upload', 'auto_receipt', 'hyc_ticket', 'test', 'update_yeji', 'city', 'citys', 'channel_downgrade', 'sync_custom', 'app_info'];
    protected $noNeedRight = '*';

    /**
     * 加载初始化
     *@ApiInternal
     * @param string $version 版本号
     * @param string $lng     经度
     * @param string $lat     纬度
     * 
     */
    public function init()
    {
        if ($version = $this->request->request('version')) {
            $lng = $this->request->request('lng');
            $lat = $this->request->request('lat');

            //配置信息
            $upload = Config::get('upload');
            //如果非服务端中转模式需要修改为中转
            if ($upload['storage'] != 'local' && isset($upload['uploadmode']) && $upload['uploadmode'] != 'server') {
                //临时修改上传模式为服务端中转
                set_addon_config($upload['storage'], ["uploadmode" => "server"], false);

                $upload = \app\common\model\Config::upload();
                // 上传信息配置后
                Hook::listen("upload_config_init", $upload);

                $upload = Config::set('upload', array_merge(Config::get('upload'), $upload));
            }

            $upload['cdnurl'] = $upload['cdnurl'] ? $upload['cdnurl'] : cdnurl('', true);
            $upload['uploadurl'] = preg_match("/^((?:[a-z]+:)?\/\/)(.*)/i", $upload['uploadurl']) ? $upload['uploadurl'] : url($upload['storage'] == 'local' ? '/api/common/upload' : $upload['uploadurl'], '', false, true);

            $content = [
                'citydata'    => Area::getCityFromLngLat($lng, $lat),
                'versiondata' => Version::check($version),
                'uploaddata'  => $upload,
                'coverdata'   => Config::get("cover"),
            ];
            $this->success('', $content);
        } else {
            $this->error(__('Invalid parameters'));
        }
    }
    /**
     * 更新用户城市所属子平台
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function updateAcct()
    {
        $user = User::all(['city' => ['<>', '']]);
        foreach ($user as $key => $value) {
            $acct = Admin::where('province',  $value['province_id'])->find();
            if ($acct) {
                $value->acct_id = $acct['acct_id'];
                $value->save();
            }
        }
        $this->success("请求成功");
    }
    /**
     * 更新用户城市
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function updateCity()
    {
        $user = User::where('city', '<>', '')
            ->where('province_id', 0)
            ->where('city_id', 0)
            ->where('area_id', 0)
            ->select();
        foreach ($user as $key => $value) {
            $city = explode('/', $value['city']);
            $provinceinfo = db('cnarea')->whereLike('short_name|name', '%' . $city[0] . '%')->where('level', 1)->find();
            if (!$provinceinfo) {
                continue;
            }
            $value->province_id = $provinceinfo['area_code'];
            $cityinfo = db('cnarea')->whereLike('short_name|name', '%' . $city[1] . '%')->where('parent_code', $provinceinfo['area_code'])->where('level', 2)->find();
            if (!$cityinfo) {
                continue;
            }
            $value->city_id = $cityinfo['area_code'];
            $areainfo = db('cnarea')->whereLike('short_name|name', '%' . $city[2] . '%')->where('parent_code', $cityinfo['area_code'])->where('level', 3)->find();
            if (!$areainfo) {
                continue;
            }
            $value->area_id = $areainfo['area_code'];
            $value->save();
        }
        $this->success("请求成功");
    }
    /**
     * 更新客户城市
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function updateCustCity()
    {
        $user = ModelCustom::where('city', '<>', '')
            ->where('province_id', 0)
            ->where('city_id', 0)
            ->where('area_id', 0)
            ->select();

        foreach ($user as $key => $value) {
            $city = explode('/', $value['city']);
            if (!isset($city[0]) || !isset($city[1]) || !isset($city[2])) {
                continue;
            }
            $provinceinfo = db('cnarea')->whereLike('short_name|name', '%' . $city[0] . '%')->where('level', 1)->find();
            if (!$provinceinfo) {
                continue;
            }
            $value->province_id = $provinceinfo['area_code'];
            $cityinfo = db('cnarea')->whereLike('short_name|name', '%' . $city[1] . '%')->where('parent_code', $provinceinfo['area_code'])->where('level', 2)->find();
            if (!$cityinfo) {
                continue;
            }
            $value->city_id = $cityinfo['area_code'];
            $areainfo = db('cnarea')->whereLike('short_name|name', '%' . isset($city[2]) ? $city[2] : '' . '%')->where('parent_code', $cityinfo['area_code'])->where('level', 3)->find();
            if (!$areainfo) {
                continue;
            }
            $value->area_id = $areainfo['area_code'];
            $value->save();
        }


        $this->success("请求成功");
    }
    /**
     * 更新客户地址城市
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function updateCustAddressCity()
    {
        $user = Address::where('city', '<>', '')
            ->where('province_id', 0)
            ->where('city_id', 0)
            ->where('area_id', 0)
            ->select();
        foreach ($user as $key => $value) {
            $city = explode('/', $value['city']);
            if (!isset($city[0]) || !isset($city[1]) || !isset($city[2])) {
                continue;
            }
            $provinceinfo = db('cnarea')->whereLike('short_name|name', '%' . $city[0] . '%')->where('level', 1)->find();
            if (!$provinceinfo) {
                continue;
            }
            $value->province_id = $provinceinfo['area_code'];
            $cityinfo = db('cnarea')->whereLike('short_name|name', '%' . $city[1] . '%')->where('parent_code', $provinceinfo['area_code'])->where('level', 2)->find();
            if (!$cityinfo) {
                continue;
            }
            $value->city_id = $cityinfo['area_code'];
            $areainfo = db('cnarea')->whereLike('short_name|name', '%' . isset($city[2]) ? $city[2] : '' . '%')->where('parent_code', $cityinfo['area_code'])->where('level', 3)->find();
            if (!$areainfo) {
                continue;
            }
            $value->area_id = $areainfo['area_code'];
            $value->save();
        }


        $this->success("请求成功");
    }
    /**
     * 城市选择(弃用)
     * @Author xy
     * @ApiMethod (POST)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    function city()
    {
        $tree = Tree::instance();
        $tree->init(collection(Area::select())->toArray(), 'pid');
        $categorylist = $tree->getTreeArray(0);
        // var_dump($categorylist);
        $this->responseMsg(0, $categorylist);
    }
    /**
     * 城市选择
     * @Author xy
     * @ApiMethod (POST)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    function citys()
    {
        $tree = Tree::instance();
        $redis = Cache::store('redis')->handler();
        $list =  $redis->get('1243areaList');
        if (!$list) {
            $tree->init(collection(db('cnarea')->whereIn('level', [1, 2, 3])->field('short_name,name,parent_code,area_code as id')->select())->toArray(), 'parent_code');
            $list = $tree->getTreeArray(0);
            $redis->set('1243areaList', json_encode($list));
        } else {
            $list = json_decode($list, true);
        }
        $this->success('', $list);
    }
    /**
     * 上传文件
     * @ApiMethod (POST)
     * @param File $file 文件流
     */
    public function upload()
    {
        (new \addons\alioss\controller\Index)->upload(true);
        return;
        Config::set('default_return_type', 'json');
        //必须设定cdnurl为空,否则cdnurl函数计算错误
        Config::set('upload.cdnurl', '');
        $chunkid = $this->request->post("chunkid");
        if ($chunkid) {
            if (!Config::get('upload.chunking')) {
                $this->error(__('Chunk file disabled'));
            }
            $action = $this->request->post("action");
            $chunkindex = $this->request->post("chunkindex/d");
            $chunkcount = $this->request->post("chunkcount/d");
            $filename = $this->request->post("filename");
            $method = $this->request->method(true);
            if ($action == 'merge') {
                $attachment = null;
                //合并分片文件
                try {
                    $upload = new Upload();
                    $attachment = $upload->merge($chunkid, $chunkcount, $filename);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
            } elseif ($method == 'clean') {
                //删除冗余的分片文件
                try {
                    $upload = new Upload();
                    $upload->clean($chunkid);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            } else {
                //上传分片文件
                //默认普通上传文件
                $file = $this->request->file('file');
                try {
                    $upload = new Upload($file);
                    $upload->chunk($chunkid, $chunkindex, $chunkcount);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            }
        } else {
            $attachment = null;
            //默认普通上传文件
            $file = $this->request->file('file');
            try {
                $upload = new Upload($file);
                $attachment = $upload->upload();
            } catch (UploadException $e) {
                $this->error($e->getMessage());
            }

            $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
        }
    }

    /**
     * 公共配置
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiSummary ()
     * @ApiBody ()
     * @ApiParams (name="name", type="integer", required=true, sample="", description="配置项：channel_franchise=渠道商申请加盟说明;shipping_address=样品寄送地址;lcontact_mobile=联系电话；goods_tag_switch=商品标签开关；income_statement=收益说明；about=培训资料；rider_rule=销售资料；shop_rule=发货列表；mode_description=模式说明；user_protocol=用户服务协议；privacy_policy=隐私政策,index_image=首页弹窗,index_image_switch=首页弹窗开关,index_image_id=首页弹窗关联公告ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function site_config()
    {

        $rej = $this->validate(
            $this->request->post(),
            [
                'name'  => 'require',
            ]
        );
        if (true !== $rej) {
            $this->responseMsg(1005, [], $rej);
        }
        $type = $this->request->post('name');
        $info = Config('site.' . $type);
        if (substr($type, strpos($type, 'image')) === 'image' && $info) {
            $info = cdnurl($info, true);
        }
        if (strpos($type, 'images') !== false && $info) {
            foreach ($info as &$v) {
                $v = cdnurl($v, true);
            }
        }
        $this->success('', $info);
    }
    /**
     * 系统配置
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiSummary ()
     * @ApiBody ()
     * @ApiParams (name="name", type="integer", required=true, sample="", description="")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function system_config()
    {

        $rej = $this->validate(
            $this->request->post(),
            [
                'name'  => 'require',
            ]
        );
        if (true !== $rej) {
            $this->responseMsg(1005, [], $rej);
        }
        $name = $this->request->post('name');
        $system = Systemconfig::where('name', $name)->where('acct_id', $this->auth->acct_id)->find();
        if (!$system) {
            $this->success('', '');
        }
        if ($system['type'] == 'image' && $system['value']) {
            $info = cdnurl($system['value'], true);
        } else {
            $info = $system['value'];
        }
        $this->success('', $info);
    }
    /**
     * @Author LK
     * @date: 2024-04-11 
     * @ApiTitle (自动收货)
     * @ApiMethod (GET)
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiParams (name="type", type="string", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function auto_receipt()
    {
        try {
            $time = time();
            // Order::where('updatetime', '<', $time - 10 * 86400)->where('status', '1')->update(['status' => '99', 'finished_time' => $time]);
            $orders = Order::where('updatetime', '<', $time - 15 * 86400)->where('status', '1')->limit(1)->select();
            foreach ($orders as $key => $v) {
                $v->status = '99';
                $v->finished_time = $time;
                $v->save();
            }
        } catch (\Throwable $th) {
            $this->error($th->getMessage());
        }
        $this->success();
    }

    public function hyc_ticket()
    {
        return json(['result' => 'success']);

        $params = $this->request->param();
        // $params['encryptMsg'] = "vJuOM1j6rmfN1M0GkuHCCLWCwAjjBf2EiEqQatisg2xf+H2wnWI503xyo/W1TiNV2u8KxjCAnN/n65hPMF4GsyCmPKikUZ+DfQCvZLG4MvltNqb4z34rCs4gvGnoi50E70cK+BZkAo4Ei0FGclSrDhJE/SZOSIClFJ+vXOv6yqSyRci/y68NDlaWuAzNO68qqey4+nrQGW5uTyUvjpeJISyjKRi/hFfMEXFB0xkAiXHE9hoLR7XZ0DJGu8qPEgU2XRDqoA8gFuM3h58KxFgZYGP/UGJR8wfdVl3D19WEPj/gHMAkYasWBKCOm7rCTovhY904I37xXZUK1HvACMcg7g==";
        $key = "f48PeEWsFjfKJkCU";
        // $input = "185eVFRuGJ1oEbc0Ot2IfAKq2zDSJelAifU26hsYTy5bHFv4UcziPlLbrh9RPnsi2u8KxjCAnN/n65hPMF4GsyCmPKikUZ+DfQCvZLG4MvltNqb4z34rCs4gvGnoi50E/QBwYnBKxwiTW5Ezg0YxTY5JA9GFBM95+HOBhdFdPtiyRci/y68NDlaWuAzNO68qBLNw9N4VOdOmjslUI9MzxiD259z7Zzr4iGhd4XjkFW65BCAwnDnVl7HWjHitf9+AXRDqoA8gFuM3h58KxFgZYGP/UGJR8wfdVl3D19WEPj/gHMAkYasWBKCOm7rCTovhY904I37xXZUK1HvACMcg7g==";
        // var_dump(base64_decode($input));

        $res = openssl_decrypt(base64_decode($params['encryptMsg']), 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
        if ($res !== false) {
            $res = json_decode($res, true);
            if (!empty($res['msgType']) && $res['msgType'] == 'APP_TICKET') {
                Cache::set('hyc_ticket', $res['bizContent']['appTicket']);
            }
        }
        // $res = decryptAES("","f48PeEWsFjfKJkCU","");
        // Log::error(var_export($params, true));
        Log::error($res);
        // var_dump($res);
        return json(['result' => 'success']);
    }

    public function test()
    {
        $api = new Jdy(['acct_id' => 67]);
        // $user = User::get(90);
        // $res = $api->addUser($user);
        // $api->getIncomeType();
        // $api->getDepartmentList();

        // $api->syncUnit();
        // $api->syncSalesman();
        // $api->syncCustomer();

        // $api->goodsList();
        // $api->accountList();
        $api->customFields();
        // $order = Order::get(21269);

        // $api->addPreCredit($order);
        // $goods = Goods::get(28);
        // $res = $api->addGoods($goods);



    }

    function sync_custom()
    {
        // $api = new Jdy();
        // $api->syncCustomer();
    }
    public function channel_downgrade()
    {
        try {
            $month_num = config('site.month_num');
            $uids = User::where('is_channel', 1)->where('channeltime', '<', strtotime("-{$month_num} month"))->field('id,nickname,is_channel,channel_level')->select();
            foreach ($uids as $k => $v) {
                $user_ids = [];
                User::digui($v['id'], $user_ids);
                $month_number = 0;
                for ($i = 1; $i <= $month_num ?? 1; $i++) {
                    $startday = date('Y-m-1', strtotime("-{$i} month"));
                    $endday = date('Y-m-t 23:59:59', strtotime("-{$i} month"));
                    $total_performance = Order::whereIn('user_id', $user_ids)->where('status', '99')->whereTime('finished_time',  'between', [$startday, $endday])->sum('total_fee');
                    $team_turnover = Channel::where('id', $v['channel_level'])->value('reduce_rules');
                    if ($total_performance >= $team_turnover) {
                        $month_number = 0;
                        break;
                    }
                    $month_number++;
                }
                if ($month_number >= 3) {
                    if ($v['channel_level'] != 1) {
                        $v->channel_level = $v['channel_level'] - 1;
                        $v->channeltime = time();
                    } else {
                        $v->channel_level = 0;
                        $v->is_channel = 0;
                        $v->channeltime = 0;
                    }
                    $v->save();
                    Channelapply::where('user_id', $v['id'])->where('channel_level', $v['channel_level'])->delete();
                }
                // $total_source_price = Commission::whereIn('source_user_id', $user_ids)->whereTime('createtime', '<', time() - 600)->where('status', '1')->sum('source_price');
                // if ($total_source_price < $team_turnover) {
                //     $v->is_channel = 0;
                //     $v->channeltime = 0;
                //     $v->save();
                //     Channelapply::where('user_id', $v['id'])->delete();
                // }
            }
        } catch (\Throwable $th) {
            $this->error($th->getMessage());
        }
        $this->success('执行成功');
        // whereTime('createtime', sprintf('-%d day', $month_num))->
    }

    //更新业绩
    function update_yeji()
    {
        $list = Order::where('status', '>', '0')->where('pay_time', 'between', [strtotime('first day of last month'), strtotime(date('Y-m-01'))])->group('acct_id')->field('acct_id,sum(total_fee) as total_fee')->select();
        foreach ($list as $key => $value) {
            $acct = Acct::get($value['acct_id']);
            if ($acct) {
                $acct->lastmonth_ach = $value['total_fee'];
                $acct->lastupdate = date('Y-m-d');
                $acct->save();
            }
        }
    }

    /**
     * 获取app信息
     * type 1 user 2 经销商
     */
    function app_info()
    {


        $type = $this->request->param('type');
        if ($type == 1) {
            $this->success('', [
                'versionCode' => config('site.versionCode'),
                'versionName' => config('site.versionName'),
                'versionInfo' => config('site.versionInfo'),
                'updateType' => config('site.updateType'),
                'downloadUrl' => config('site.downloadUrl'),
            ]);
        } else {
            $this->success('', [
                'versionCode' => config('site.versionCode1'),
                'versionName' => config('site.versionName1'),
                'versionInfo' => config('site.versionInfo1'),
                'updateType' => config('site.updateType1'),
                'downloadUrl' => config('site.downloadUrl1'),
            ]);
        }
    }
    public function yy_notify()
    {
        $data = request()->post();
        extract($data);
        if ($data['bussinessType'] != 'SOCIALTASK') {
            return json([
                'status' => "000000",
                'msg' => '请求成功',
            ]);
        }
        Log::error('用友提现回调' . var_export($data, true));
        try {

            if ($data['bussinessData']['settlementStatus'] == '50') {
                $withdrawlog = Withdrawlog::where('sn', $data['bussinessData']['targetServiceNum'])->where('bourEmpNo', $data['bussinessData']['targetServiceNo'])->find();
                if ($withdrawlog) {
                    $withdrawlog->status = 1;
                    $withdrawlog->uptime = time();
                    $withdrawlog->save();
                }
            }
            if ($data['bussinessData']['settlementStatus'] == '70') {
                $withdrawlog = Withdrawlog::where('sn', $data['bussinessData']['targetServiceNum'])->where('bourEmpNo', $data['bussinessData']['targetServiceNo'])->find();
                if ($withdrawlog) {
                    $withdrawlog->status = 2;
                    $withdrawlog->save();
                }
            }
            //code...
        } catch (\Throwable $th) {
            Log::error('用友提现错误' . var_export($th->getMessage(), true));
        }
        return json([
            'status' => "000000",
            'msg' => '请求成功',
        ]);
    }
}
